package com.lollipop.programming.thread.sequential;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @Author Lollipop
 * @Date 2025/7/28 15:44
 * @Description 多线程顺序执行 - 线程condition Demo
 * @Version 1.0
 */
@Slf4j
public class ThreadCondition {
    private static final Lock lock = new ReentrantLock();
    private static final Condition conditionA = lock.newCondition();
    private static final Condition conditionB = lock.newCondition();
    private static boolean aFinished = false;
    private static boolean bFinished = false;

    public static void main(String[] args) {
        Thread threadA = new Thread(() -> {
            lock.lock();
            try {
                log.info("任务A开始执行");
                Thread.sleep(1000);
                log.info("任务A执行完成");
                aFinished = true;
                conditionA.signal();
            } catch (InterruptedException e) {
                log.error("任务A执行异常：{}", e.getMessage());
            } finally {
                lock.unlock();
            }
        });

        Thread threadB = new Thread(() -> {
            lock.lock();
            try {
                while (!aFinished) {
                    conditionA.await();
                }
                log.info("任务B开始执行");
                Thread.sleep(1000);
                log.info("任务B执行完成");
                bFinished = true;
                conditionB.signal();
            } catch (InterruptedException e) {
                log.error("任务B执行异常：{}", e.getMessage());
            } finally {
                lock.unlock();
            }
        });

        Thread threadC = new Thread(() -> {
            lock.lock();
            try {
                while (!bFinished) {
                    conditionB.await();
                }
                log.info("任务C开始执行");
                Thread.sleep(1000);
                log.info("任务C执行完成");
            } catch (InterruptedException e) {
                log.error("任务C执行异常：{}", e.getMessage());
            } finally {
                lock.unlock();
            }
        });

        threadA.start();
        threadB.start();
        threadC.start();
    }
}
